package ar.edu.utn.frsf.tpae.a2012.g04.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import ar.edu.utn.frsf.tpae.a2012.g04.dao.ClienteDao;
import ar.edu.utn.frsf.tpae.a2012.g04.dominio.Cliente;
import ar.edu.utn.frsf.tpae.a2012.g04.dominio.Cuenta;

public class ClienteHibernateDao implements ClienteDao{

	  private SessionFactory sessionFactory = new AnnotationConfiguration()
	      .configure().buildSessionFactory();
	  
	@Override
	public Cliente persistir(Cliente cliente) {
		Session session = sessionFactory.openSession();
	    session.beginTransaction();
	    session.saveOrUpdate(cliente);
	    session.getTransaction().commit();
	    session.close();
	    return cliente;
	}

	@Override
	public void eliminar(Cliente cliente) {
		Session session = sessionFactory.openSession();
	    session.beginTransaction();
	    session.delete(cliente);
	    session.getTransaction().commit();
	    session.close();
	}

	@SuppressWarnings("unchecked")
	  @Override
	  public List<Cliente> listar() {
	    Session session = sessionFactory.openSession();
	    Query query = session.createQuery("from " + Cliente.class.getName());
	    List<Cliente> list = query.list();
	    session.close();
		return list;
	  }

	@Override
	public Cliente buscarPorId(Integer id) {
		Session session = sessionFactory.openSession();
		return (Cliente) session.get(Cliente.class, id);
	}

	@Override
	public Cliente buscarPorNumero(String numero) {
		Session session = sessionFactory.openSession();
	    Query query = session.createQuery("from " + Cliente.class.getName() + " cli where cli.numero = :numero" );
	    query.setString("numero", numero);
	    Cliente cliente = (Cliente) query.uniqueResult();
		return cliente;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Cuenta> listarCuentas(Cliente cliente) {
	    Session session = sessionFactory.openSession();
	    Query query = session.createQuery("from " + Cuenta.class.getName() + " cta where cta.cliente.id = :id" );
	    query.setInteger("id", cliente.getId());
	    List<Cuenta> list = query.list();
	    session.close();
		return list;
	}

}
